//
//  TTLoginViewController.m
//  TeacherNet
//
//  Created by slz on 2017/11/24.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "TTLoginViewController.h"
#import "MFWUserLoginManager.h"
#import "RegisterViewController.h"
#import "ForgetPasswordViewController.h"

#define kTextFiledBoderColor [UIColor colorWithRGB:0xb5b6b8]


@implementation TTTextFiled
- (instancetype)initWithPlaceholder:(NSString *)placeHolder andLeftImageName:(NSString *)imageName
{
    self = [super init];
    if (self){
        self.layer.borderWidth = 1.5;
        self.layer.borderColor = kTextFiledBoderColor.CGColor;
        self.borderStyle = UITextBorderStyleNone;
        self.placeholder = placeHolder;
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
        imageView.image = [UIImage imageNamed:imageName];
        self.leftViewMode = UITextFieldViewModeAlways;
        self.leftView = imageView;
        self.textColor = kTextFiledBoderColor;
    }
    return self;
}

- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
    CGRect iconRect = [super leftViewRectForBounds:bounds];
    iconRect.origin.x += 15; //像右边偏15
    return iconRect;
}

- (CGRect)textRectForBounds:(CGRect)bounds{
    
    return CGRectInset(bounds, 45, 0);
    
}

//控制文本的位置
- (CGRect)editingRectForBounds:(CGRect)bounds{
    
    return CGRectInset(bounds, 45, 0);
}

@end

@implementation NomalLoginView
- (instancetype)init
{
    self = [super init];
    if (self){
        _textFiled1 = [[TTTextFiled alloc]initWithPlaceholder:@"用户名" andLeftImageName:@"user_login_useraccount"];
        [self addSubview:_textFiled1];
        [_textFiled1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left).offset(20);
            make.right.mas_equalTo(self.mas_right).offset(-20);
            make.top.mas_equalTo(self.mas_top).offset(10);
            make.height.mas_equalTo(40);
        }];
        
        _textFiled2 = [[TTTextFiled alloc]initWithPlaceholder:@"密码" andLeftImageName:@"user_login_password"];
        _textFiled2.keyboardType = UIKeyboardTypeASCIICapable;
        _textFiled2.secureTextEntry = YES;
        [self addSubview:_textFiled2];
        [_textFiled2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left).offset(20);
            make.right.mas_equalTo(self.mas_right).offset(-20);
            make.top.mas_equalTo(_textFiled1.mas_bottom).offset(30);
            make.height.mas_equalTo(40);
        }];
        
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.backgroundColor = kLoginGreenColor;
        [_loginButton setTitle:@"登     录" forState:UIControlStateNormal];
        _loginButton.titleLabel.fontSize = 16;
        [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self addSubview:_loginButton];
        [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(_textFiled2);
            make.top.mas_equalTo(_textFiled2.mas_bottom).offset(30);
            make.height.mas_equalTo(40);
        }];
        
        _fogetPassword = [UIButton buttonWithType:UIButtonTypeCustom];
        [_fogetPassword setTitle:@"忘记密码" forState:UIControlStateNormal];
        _fogetPassword.titleLabel.fontSize = 14;
        [_fogetPassword setTitleColor:kLight_TextColor_Default forState:UIControlStateNormal];
        [self addSubview:_fogetPassword];
        [_fogetPassword mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(_loginButton.mas_right);
            make.width.mas_equalTo(60);
            make.top.mas_equalTo(_loginButton.mas_bottom).offset(15);
            make.height.mas_equalTo(20);
        }];
        
    }
    return self;
}


@end

@implementation PhoneLoginView
- (instancetype)init
{
    self = [super init];
    if (self){
        CGFloat  textFieldWidth = (kScreenWidth - 60) * .5;
        
        _textFiled1 = [[TTTextFiled alloc]initWithPlaceholder:@"手机号" andLeftImageName:@"user_login_useraccount"];
        _textFiled1.keyboardType = UIKeyboardTypePhonePad;
        [self addSubview:_textFiled1];
        [_textFiled1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left).offset(20);
            make.right.mas_equalTo(self.mas_right).offset(-20);
            make.top.mas_equalTo(self.mas_top).offset(10);
            make.height.mas_equalTo(40);
        }];
        
        _textFiled2 = [[TTTextFiled alloc]initWithPlaceholder:@"验证码" andLeftImageName:@"user_login_password"];
        _textFiled2.keyboardType = UIKeyboardTypePhonePad;
        [self addSubview:_textFiled2];
        [_textFiled2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left).offset(20);
            make.width.mas_equalTo(textFieldWidth);
            make.top.mas_equalTo(_textFiled1.mas_bottom).offset(30);
            make.height.mas_equalTo(40);
        }];
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(timeAction)];
        _getMessageButton = [UILabel new];
        _getMessageButton.text = @"获取短信验证码";
        _getMessageButton.textAlignment = NSTextAlignmentCenter;
        _getMessageButton.fontSize = kFont_Size_Cotent_Nomal;
        _getMessageButton.layer.borderWidth = 1.5;
        _getMessageButton.layer.borderColor = kTextFiledBoderColor.CGColor;
        _getMessageButton.userInteractionEnabled = YES;
        [_getMessageButton addGestureRecognizer:tap];
        _getMessageButton.backgroundColor = [UIColor colorWithRGB:0xF5F5F6];
        _getMessageButton.textColor = [UIColor colorWithRGB:0x919394];
        [self addSubview:_getMessageButton];
        [_getMessageButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(textFieldWidth, 40));
            make.right.mas_equalTo(self.mas_right).offset(-20);
            make.top.mas_equalTo(_textFiled2.mas_top);
            }];
        }
    
        _indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
        [_getMessageButton addSubview:_indicatorView];
        [_indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(_getMessageButton);
        }];
    
    _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginButton.backgroundColor = kLoginGreenColor;
    [_loginButton setTitle:@"登     录" forState:UIControlStateNormal];
    [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _loginButton.titleLabel.fontSize = 16;
    [self addSubview:_loginButton];
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(_textFiled1);
        make.top.mas_equalTo(_textFiled2.mas_bottom).offset(30);
        make.height.mas_equalTo(40);
    }];
    return self;
}

- (void)timeAction{
    NSString * phoneString = _textFiled1.text;
    if (![self validateNumber:phoneString]){
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码~"];
        return;
    }
    _getMessageButton.text = @"";
    [_indicatorView startAnimating];
    _getMessageButton.exclusiveTouch = YES;
    _getMessageButton.userInteractionEnabled = NO;
    [BaseHttpTool get:kAPI_APP_MESSAGE_VALIDE params:@{@"phone":phoneString} success:^(id responseObj) {
        [_indicatorView stopAnimating];
        NSString * result = [responseObj stringValueForKey:@"status"];
        if ([result isEqualToString:@"0"]){
            [self timeStart];
        }else{
            [SVProgressHUD showErrorWithStatus:@"获取验证码失败~"];
            _getMessageButton.text = @"获取短信验证码";
            self.getMessageButton.userInteractionEnabled = YES;
        }
    } failure:^(NSError *error) {
        _getMessageButton.text = @"获取短信验证码";
        [_indicatorView stopAnimating];
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        self.getMessageButton.userInteractionEnabled = YES;
    }];
}

- (void)timeStart{
    __block int time = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (time < 1){
            dispatch_source_cancel(_timer);// gcd timer中必须要有 cancle 这个timer的代码 否则代码将无法执行。
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString * defaultTimeString = @"获取验证码";
                self.getMessageButton.text = defaultTimeString;
                self.getMessageButton.userInteractionEnabled = YES;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                time--;
                NSString *timeString = [NSString stringWithFormat:@"%d",time];
                self.getMessageButton.text = timeString;
            });
        }
    });
    dispatch_resume(_timer);
}

- (BOOL)validateNumber:(NSString *)textString
{
    if (textString.length != 11){
        return NO;
    }
    NSString* number=@"^[0-9]+$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}

@end

@interface TTLoginViewController ()
@property (nonatomic,strong) UIView *sliderView;
@property (nonatomic,strong) TTScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *nomalLoginButton;
@property (weak, nonatomic) IBOutlet UIButton *phoneLoginButton;

@end

@implementation TTLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [SVProgressHUD setMinimumDismissTimeInterval:3];
    [SVProgressHUD setMaximumDismissTimeInterval:3];
    self.showNavigationBar = YES;
    [self setControllerTitle:@"用户登录"];
    UIBarButtonItem * rightItem = [UIBarButtonItem itemWIthTitle:@"注册" addTarget:self action:@selector(registerAction) andTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15] ,NSForegroundColorAttributeName:kLoginGreenColor}];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self initViews];
    
    
    // Do any additional setup after loading the view from its nib.
}

- (void)initViews
{
    _sliderView = [UIView new];
    _sliderView.backgroundColor = kLoginGreenColor;
    _sliderView.size = CGSizeMake(60, 4);
    _sliderView.centerX = kScreenWidth * .25;
    _sliderView.top = 60;
    [self.view addSubview:_sliderView];
    
    _scrollView = [TTScrollView new];
    _scrollView.pagingEnabled = YES;
    _scrollView.scrollEnabled = NO;
    [self.view addSubview:_scrollView];
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_nomalLoginButton.mas_bottom).offset(50);
        make.left.and.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(-150);
    }];
    
    _phoneView = [PhoneLoginView new];
    _nomalView = [NomalLoginView new];
    [_scrollView addSubview:_nomalView];
    [_scrollView addSubview:_phoneView];
    
    [_nomalView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.and.bottom.mas_equalTo(_scrollView);
        make.width.mas_equalTo(kScreenWidth);
        make.height.mas_equalTo(_scrollView.mas_height);
    }];
    
    [_phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_nomalView.mas_right);
        make.top.mas_equalTo(_scrollView.mas_top);
        make.bottom.mas_equalTo(_scrollView.mas_bottom);
        make.width.mas_equalTo(kScreenWidth);
        make.right.mas_equalTo(_scrollView.mas_right);
        make.height.mas_equalTo(_scrollView.mas_height);
    }];
    [_nomalView.loginButton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    [_phoneView.loginButton addTarget:self action:@selector(phoneLoginAction) forControlEvents:UIControlEventTouchUpInside];
    [_nomalView.fogetPassword addTarget:self action:@selector(forgetAction) forControlEvents:UIControlEventTouchUpInside];

}

- (void)forgetAction{
    ForgetPasswordViewController * controller = [[ForgetPasswordViewController alloc]init];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)phoneLoginAction{
    NSString * phoneStirng = _phoneView.textFiled1.text;
    NSString * message = _phoneView.textFiled2.text;
    if (![self validateNumber:phoneStirng]){
        [self.view showTip:@"请输入正确的手机号~"];
        return;
    }
    if (!message || message.length == 0){
        [self.view showTip:@"请输入验证码~"];
        return;
    }
    
    [self.view endEditing:YES];
    [SVProgressHUD showWithStatus:@"登录中..."];
    [SVProgressHUD setMinimumDismissTimeInterval:3];
    
    [[MFWUserLoginManager sharedInstance] loginWithPhone:phoneStirng messageNumber:message finisheHandler:^(BOOL success, MFWUserInfo *userInfo, NSError *error) {
        if (!success){
            [SVProgressHUD showErrorWithStatus:[error.userInfo stringValueForKey:@"errorMsg"]];
        }else
        {
            [SVProgressHUD dismiss];
            [self dismissViewControllerAnimated:YES completion:NULL];
        }
    }];
}

- (BOOL)validateNumber:(NSString *)textString
{
    if (textString.length != 11){
        return NO;
    }
    NSString* number=@"^[0-9]+$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}

- (void)loginAction{
    [self.view endEditing:YES];
    NSString * phoneStirng = _nomalView.textFiled1.text;
    NSString * message = _nomalView.textFiled2.text;
    if (!phoneStirng || phoneStirng.length == 0){
        [self.view showTip:@"请输入用户名~"];
        return;
    }
    if (!message || message.length == 0){
        [self.view showTip:@"请输入密码~"];
        return;
    }
    [SVProgressHUD showWithStatus:@"登录中..."];
    
    [[MFWUserLoginManager sharedInstance] loginWithOIDUserName:_nomalView.textFiled1.text password:_nomalView.textFiled2.text finisheHandler:^(BOOL success, MFWUserInfo *userInfo, NSError *error) {
        if (!success){
            [SVProgressHUD showErrorWithStatus:[error.userInfo stringValueForKey:@"errorMsg"]];
        }else
        {
            [SVProgressHUD dismiss];
            [self dismissViewControllerAnimated:YES completion:NULL];
        }
    }];
}

- (void)registerAction
{
    RegisterViewController * registerController = [RegisterViewController new];
    [self.navigationController pushViewController:registerController animated:YES];
}
- (IBAction)normalLoginAction:(id)sender {
    [self.view endEditing:YES];
    if ([sender isEqual:self.nomalLoginButton])
    {
        
        [UIView animateWithDuration:.3 animations:^{
            _sliderView.centerX = kScreenWidth * .25;
            _scrollView.contentOffset = CGPointMake(0, 0);
        }];
    }else
    {
        [UIView animateWithDuration:.3 animations:^{
            _sliderView.centerX = kScreenWidth * .75;
            _scrollView.contentOffset = CGPointMake(kScreenWidth, 0);
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
